package etc.com.market;

import java.util.ArrayList;
import java.util.Date;

import oauth.signpost.OAuth;

import org.json.JSONObject;
import org.json.JSONTokener;

import Controls.JsonDataHelper;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.ecs.android.sample.twitter.PrepareRequestTokenActivity;
import com.ecs.android.sample.twitter.TwitterUtils;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;

import etc.com.sql.DBAdapter;

public class ProductDetail extends Activity implements OnItemClickListener {
	/** Called when the activity is first created. */
	ArrayList<String> arrtext = new ArrayList<String>();
	int[] idimage = new int[6];
	int[] idimage1 = new int[6];
	String proId;
	String prodname;
	String imagename;
	String previous;
	String storename;
	String str;
	private ViewFlipper vf;
	private float oldTouchValue;
	private static final int REQUEST_CODE = 10;

	private SharedPreferences prefs;
	private final Handler mTwitterHandler = new Handler();

	final Runnable mUpdateTwitterNotification = new Runnable() {
		public void run() {
			Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG)
					.show();
		}
	};

	// --------facebook variable-------

	private Facebook mFacebook;
	private CheckBox mFacebookCb;
	private ProgressDialog mProgress;

	private Handler mRunOnUi = new Handler();

	private static final String APP_ID = "app id here";
	private static final String[] PERMISSIONS = new String[] {"publish_stream", "read_stream", "offline_access"};
	private Cursor cursor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.productdetail);
		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}
		vf = (ViewFlipper) findViewById(R.id.layoutswitcher);

		String messageReceive = extras.getString("message");
		proId = extras.getString("ProductID");
		mProgress = new ProgressDialog(this);

		mFacebook = new Facebook(APP_ID);

		ImageView tweet = (ImageView) findViewById(R.id.tweet);
		ImageView facebook = (ImageView) findViewById(R.id.facebook);
		tweet.setOnClickListener(new View.OnClickListener() {
			/**
			 * Send a tweet. If the user hasn't authenticated to Tweeter yet,
			 * he'll be redirected via a browser to the twitter login page. Once
			 * the user authenticated, he'll authorize the Android application
			 * to send tweets on the users behalf.
			 */
			public void onClick(View v) {
				if (TwitterUtils.isAuthenticated(prefs)) {
					sendTweet();
				} else {
					Intent i = new Intent(getApplicationContext(),
							PrepareRequestTokenActivity.class);
					i.putExtra("tweet_msg", getTweetMsg());
					startActivity(i);
					overridePendingTransition(R.anim.fadein,
			                R.anim.fadeout);
				}
			}
		});

		facebook.setOnClickListener(new View.OnClickListener() {
			/**
			 * Send a tweet. If the user hasn't authenticated to Tweeter yet,
			 * he'll be redirected via a browser to the twitter login page. Once
			 * the user authenticated, he'll authorize the Android application
			 * to send tweets on the users behalf.
			 */
			public void onClick(View v) {

				SessionStore.restore(mFacebook, getApplicationContext());

				if (mFacebook.isSessionValid()) {
					mFacebookCb.setChecked(true);

					String name = SessionStore.getName(getApplicationContext());
					name = (name.equals("")) ? "Unknown" : name;

					mFacebookCb.setText("  Facebook  (" + name + ")");
					postToFacebook("test from supper market android application");
				}else{
					mFacebook.authorize(ProductDetail.this, PERMISSIONS, -1, new FbLoginDialogListener());
				}
				
				
			}
		});

		if (messageReceive != null) {
			str = messageReceive.toString();

			previous = str.substring(0, str.indexOf(";"));
			str = str.substring(str.indexOf(";") + 1);

			storename = str.substring(0, str.indexOf(";"));
			str = str.substring(str.indexOf(";") + 1);

			prodname = str.substring(0, str.indexOf(";"));
			imagename = str.substring(str.indexOf(";") + 1);
		}

		TextView v = (TextView) findViewById(R.id.storename);
		v.setText(storename);

//		TextView v1 = (TextView) findViewById(R.id.headerprevious);
//		v1.setText(previous);
		
		DBAdapter dbAdapter = new DBAdapter(getApplicationContext());
		cursor = dbAdapter.getProductDetailsById(proId);
		cursor.moveToNext();
		
		TextView view = (TextView) findViewById(R.id.btnNext);
		view.setText(cursor.getString(1));
		
		TextView view11 = (TextView) findViewById(R.id.btnNext1);
		view11.setText(cursor.getString(1));

		TextView view1 = (TextView) findViewById(R.id.productname);
		view1.setText(cursor.getString(1));
		
		TextView view12 = (TextView) findViewById(R.id.productname1);
		view12.setText(cursor.getString(1));
		
		String imageStr = cursor.getString(8);
		ImageView ImageView = (ImageView) findViewById(R.id.productpicture);
		ImageView ImageView1 = (ImageView) findViewById(R.id.productpicture1);
		imageStr = imageStr.substring(1, imageStr.length() - 1);
		String[] images = imageStr.split(",");
		String imageString1 = images[0].trim();
		if(imageString1 != null){
			if(!imageString1.equals("")){
				imageString1 = imageString1.substring(1, imageString1.length() - 1);
			}else{
				imageString1 = "";
			}
			
		}
		String imageValue1 = JsonDataHelper.getImageContent(imageString1);
		byte[] decodeBytes1 = Base64.decode(imageValue1.getBytes(), Base64.DEFAULT);
		Bitmap bm1 = BitmapFactory.decodeByteArray(decodeBytes1, 0, decodeBytes1.length);
		ImageView.setImageBitmap(bm1);
		System.out.println("IMAGE LENGTH: " + images.length);
		if(images.length >= 2){
			String imageString2 = images[1].trim();
			if(imageString2 != null){
				if(!imageString2.equals("")){
					imageString2 = imageString2.substring(1, imageString2.length() - 1);
				}else{
					imageString2 = "";
				}
				
			}
			String imageValue2 = JsonDataHelper.getImageContent(imageString1);
			byte[] decodeBytes2 = Base64.decode(imageValue2.getBytes(), Base64.DEFAULT);
			Bitmap bm2 = BitmapFactory.decodeByteArray(decodeBytes2, 0, decodeBytes2.length);
			ImageView1.setImageBitmap(bm2);
		}
		
		ImageView.setScaleType(ScaleType.FIT_XY);
		TextView productdesc = (TextView) findViewById(R.id.productdesc);
		productdesc
				.setText(cursor.getString(4));

		TextView productdesc1 = (TextView) findViewById(R.id.productdesc1);
		productdesc1
				.setText(cursor.getString(4));
		cursor.close();

	}

	// function use for footer button ==============================
	public void Previous(View view) {
		//onClickPre(view, ("店舗詳細;" + storename));
		finish();
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void Home(View view) {
		Intent i = new Intent(this, StoreTopPage.class);
		i.putExtra("message", storename);
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void SearchProduct(View view) {
		onClickSearch(view, ("店舗詳細;" + storename));
	}

	public void SpecifyProduct(View view) {
		onClickSpec(view, ("店舗詳細;" + storename));
	}

	public void Info(View view) {
		onClickInfo(view, storename);
	}

	public void Search(View view) {
		onClick(view, ("店舗詳細;" + storename));
	}
	
	public void Contact(View view) {
		onClick(view, ("店舗詳細;" + storename));
	}

	// ===================================================================

	public void onClick(View view, String message) {
		cursor.close();
		Intent i = new Intent(this, MeatAct.class);
		i.putExtra("message", message);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}
	
	public void onImageClick(View v) {
//		// TODO Auto-generated method stub
//		Intent i = new Intent(this, ImageZoomActivity.class);
//		i.putExtra("productId", proId);
//		i.putExtra("imageIndex", 0);
//		i.putExtra("image", R.drawable.product1);
//		i.putExtra("message", "店舗詳細;" + storename);
//		// Set the request code to any code you like, you can identify the
//		// callback via this code
//		startActivity(i);
//		overridePendingTransition(R.anim.fadein,
//                R.anim.fadeout);
		return;
	}
	
	public void onImage2Click(View v) {
		// TODO Auto-generated method stub
//		Intent i = new Intent(this, ImageZoomActivity.class);
//		i.putExtra("image",R.drawable.product2);
//		i.putExtra("message", "店舗詳細;" + storename);
//		// Set the request code to any code you like, you can identify the
//		// callback via this code
//		startActivity(i);
//		overridePendingTransition(R.anim.fadein,
//                R.anim.fadeout);
		return;
	}

	public void onClickPre(View view, String message) {
		cursor.close();
		Intent i = new Intent(this, MeatAct.class);
		// i.putExtra("message", message);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void onClickSpec(View view, String message) {
		cursor.close();
		Intent i = new Intent(this, ListitemActivity.class);
		i.putExtra("message", message);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void onClickSearch(View view, String message) {
		cursor.close();
		Intent i = new Intent(this, SearchOursProducts.class);
		i.putExtra("message", message);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void onClickInfo(View view, String message) {
		cursor.close();
		Intent i = new Intent(this, InfomationAct.class);
		i.putExtra("message", message);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}
	
	public void onClickContact(View view, String message) {
		cursor.close();
		Intent i = new Intent(this, SenmailActivity.class);
		i.putExtra("message", message);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void morePictures(View view) {
		cursor.close();
		Intent i = new Intent(this, moreImage.class);
		i.putExtra("productId", proId);
		i.putExtra("message",
				"Product Detail;" + storename + ";" + imagename.toString());
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void viewVideo(View view) {
		cursor.close();
		Intent i = new Intent(this, ViewVideo.class);
		i.putExtra("message",
				"Product Detail;" + storename + ";" + imagename.toString());
		i.putExtra("productId", proId);
		// Set the request code to any code you like, you can identify the
		// callback via this code
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// Toast.makeText(this, "CHON:"+arg2, Toast.LENGTH_SHORT).show();
		// Intent intent = new Intent(this, SpecifyProduct.class);
		// startActivity(intent);
	}

	public class ImageAdapter extends BaseAdapter {
		private Context mContext;

		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return arrtext.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		// create a new ImageView for each item referenced by the Adapter
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(mContext);

			View row = inflater.inflate(R.layout.rownull, parent, false);

			// ImageView icon=(ImageView)row.findViewById(R.id.iconfile);
			// TextView label=(TextView)row.findViewById(R.id.namefile);
			//
			// label.setText(arrtext.get(position));
			// // label1.setText(arrtext.get(position));
			// icon.setImageResource(idimage[position]);

			return row;
		}
	}

	// ----flip code ----------

	public static Animation inFromRightAnimation() {

		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(400);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	public static Animation outToLeftAnimation() {
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoLeft.setDuration(400);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	// for the next movement
	public static Animation inFromLeftAnimation() {
		Animation inFromLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromLeft.setDuration(400);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}

	public static Animation outToRightAnimation() {
		Animation outtoRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoRight.setDuration(400);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}

	@Override
	public boolean onTouchEvent(MotionEvent touchevent) {
		switch (touchevent.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			oldTouchValue = touchevent.getX();
			break;
		}
		case MotionEvent.ACTION_UP: {
			float currentX = touchevent.getX();
			if (oldTouchValue < currentX) {
				vf.setInAnimation(inFromLeftAnimation());
				vf.setOutAnimation(outToRightAnimation());
				vf.showNext();
			}
			if (oldTouchValue > currentX) {
				vf.setInAnimation(inFromRightAnimation());
				vf.setOutAnimation(outToLeftAnimation());
				vf.showPrevious();
			}
			break;
		}
		}
		return false;
	}

	// ---------twitter code -----------

	private String getTweetMsg() {
		return "Tweeting from Android App at " + new Date().toLocaleString();
	}

	public void sendTweet() {
		Thread t = new Thread() {
			public void run() {

				try {
					TwitterUtils.sendTweet(prefs, getTweetMsg());
					mTwitterHandler.post(mUpdateTwitterNotification);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

		};
		t.start();
	}

	private void clearCredentials() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		final Editor edit = prefs.edit();
		edit.remove(OAuth.OAUTH_TOKEN);
		edit.remove(OAuth.OAUTH_TOKEN_SECRET);
		edit.commit();
	}
	
	// --- facebook function -----
	
	private void postToFacebook(String review) {	
		mProgress.setMessage("Posting ...");
		mProgress.show();
		
		AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
		
		Bundle params = new Bundle();
    		
		params.putString("message", review);
		params.putString("name", "Dexter");
		params.putString("caption", "londatiga.net");
		params.putString("link", "http://www.londatiga.net");
		params.putString("description", "Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk");
		params.putString("picture", "http://twitpic.com/show/thumb/6hqd44");
		
		mAsyncFbRunner.request("me/feed", params, "POST", new WallPostListener());
	}

	private final class WallPostListener extends BaseRequestListener {
        public void onComplete(final String response) {
        	mRunOnUi.post(new Runnable() {
        		public void run() {
        			mProgress.cancel();
        			
        			Toast.makeText(ProductDetail.this, "Posted to Facebook", Toast.LENGTH_SHORT).show();
        		}
        	});
        }
    }
	
	private final class FbLoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionStore.save(mFacebook, ProductDetail.this);
           
   		 
            getFbName();
        }

        public void onFacebookError(FacebookError error) {
           Toast.makeText(ProductDetail.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
           
        }
        
        public void onError(DialogError error) {
        	Toast.makeText(ProductDetail.this, "Facebook connection failed", Toast.LENGTH_SHORT).show(); 
        	
        }

        public void onCancel() {
        }
    }
	
	private void getFbName() {
		mProgress.setMessage("Finalizing ...");
		mProgress.show();
		
		new Thread() {
			@Override
			public void run() {
		        String name = "";
		        int what = 1;
		        
		        try {
		        	String me = mFacebook.request("me");
		        	
		        	JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue();
		        	name = jsonObj.getString("name");
		        	what = 0;
		        } catch (Exception ex) {
		        	ex.printStackTrace();
		        }
		        
		        mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name));
			}
		}.start();
	}
	
	private void fbLogout() {
		mProgress.setMessage("Disconnecting from Facebook");
		mProgress.show();
			
		new Thread() {
			@Override
			public void run() {
				SessionStore.clear(ProductDetail.this);
		        	   
				int what = 1;
					
		        try {
		        	mFacebook.logout(ProductDetail.this);
		        		 
		        	what = 0;
		        } catch (Exception ex) {
		        	ex.printStackTrace();
		        }
		        	
		        mHandler.sendMessage(mHandler.obtainMessage(what));
			}
		}.start();
	}
	
	private Handler mFbHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			
			if (msg.what == 0) {
				String username = (String) msg.obj;
		        username = (username.equals("")) ? "No Name" : username;
		            
		        SessionStore.saveName(username, ProductDetail.this);
		        
		         
		        Toast.makeText(ProductDetail.this, "Connected to Facebook as " + username, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ProductDetail.this, "Connected to Facebook", Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			
			if (msg.what == 1) {
				Toast.makeText(ProductDetail.this, "Facebook logout failed", Toast.LENGTH_SHORT).show();
			} else {
	        	   
				Toast.makeText(ProductDetail.this, "Disconnected from Facebook", Toast.LENGTH_SHORT).show();
			}
		}
	};
}
